package com.drools.example.service;

import java.util.List;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.Message;
import org.kie.api.runtime.KieContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.drools.example.model.Rule;
import com.drools.example.repository.RuleRepository;

/**
 * 功能描述,该部分必须以中文句号结尾。
 *
 * @author panqingcui
 * @create 2018-08-20 15:30
 */
@Service
public class ReloadDroolsRulesService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReloadDroolsRulesService.class);
    public static KieContainer kieContainer;

    @Autowired
    private RuleRepository ruleRepository;
    public  void reload(){
        KieContainer kieContainer=loadContainerFromString(loadRules());
        ReloadDroolsRulesService.kieContainer = kieContainer;
    }

    private List<Rule> loadRules(){
        List<Rule> rules=ruleRepository.findAll();
        LOGGER.info("规则列表：{}",rules);
        return rules;
    }

    private  KieContainer loadContainerFromString(List<Rule> rules) {
        long startTime = System.currentTimeMillis();
        KieServices ks = KieServices.Factory.get();
        KieRepository kr = ks.getRepository();
        KieFileSystem kfs = ks.newKieFileSystem();

        for (Rule rule:rules) {
            String  drl=rule.getContent();
            kfs.write("src/main/resources/" + drl.hashCode() + ".drl", drl);
        }

        KieBuilder kb = ks.newKieBuilder(kfs);

        kb.buildAll();
        if (kb.getResults().hasMessages(Message.Level.ERROR)) {
            throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());
        }
        long endTime = System.currentTimeMillis();
        LOGGER.info("Time to build rules :{} ms", (endTime - startTime));
        startTime = System.currentTimeMillis();
        KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
        endTime = System.currentTimeMillis();
        LOGGER.info("TTime to load container :{} ms", (endTime - startTime));
        return kContainer;
    }
}
